<?php
	
	$tableWriter = new CmsTableWriter(CMS_AUTH_FORMAT,$db);
	$tableWriter2 = new CmsTableWriter("user",$db);
	$tableWriter3 = new CmsTableWriter("usergroup",$db);
	$error = false;
	
	if (!isset($username)) {
		$username = null;
	}
	
	//if (!$user->userType = "0") {
	//		$error = "Sorry Dave... Only Super User can edit user groups.";
	//}
	//check that user has authorisation for certain links
	$authReader = new CmsTableWriter(CMS_AUTH_FORMAT,$db);
	if ($authReader->isReady()){
		$authReader->resetCustomIterator(" WHERE username='$username' LIMIT 1");
		$authInfo = $authReader->nextItem();
		if (!($authInfo->usertype < 2)) {
			$error = "Sorry Dave... Only Super User can edit user groups.";
		}
	}		
		
	$groups = extractStringWithKeyFromArray("groups", $_REQUEST);
	$uid = extractStringWithKeyFromArray("uid", $_REQUEST);
	$userType = extractStringWithKeyFromArray("userType", $_REQUEST);
	$uGroups = extractStringWithKeyFromArray("uGroups", $_REQUEST);
	$userGroup = extractStringWithKeyFromArray("userGroup", $_REQUEST);
	
	function editUser($groups,$uid,$db) {
		//ideally begin here..
		if(!isset($uid) || $uid == null || $uid == '' || !is_numeric($uid)) {
			return false;
		}
		$query = "DELETE FROM usergroup WHERE uid='".$uid."' ";
		$db->executeQuery($query);
		$query = "INSERT INTO usergroup (uid, gid) VALUES ";
		$count = 1;
		while (list($key, $val) = each($groups)) {
			// push ("v1","v2") onto array..
			if($count != 1) {
				$query .=",";
			} 
			$count++;
			$query .= " (\"$uid\", \"$val\")";
		}
		//echo $query;
		$db->executeQuery($query);
		
		/*"INSERT INTO foo (column1,column2) VALUES ("v1","v2"),("v1","v2"),("v1","v2");
		implode array with commas and make query string..
		test that it all works..*/		
		
		// ideally if okay.. commit otherwise rollback..
		
		echo "<br><br><br>Data added.<br><br><br>";
	}
	
	if ($uid) {
		$user = $tableWriter->readItem($uid);
		$isAdding = false;
		if (!$user) {
			$error = "<b>USER NOT FOUND</b>";
		}
	} else {
		$isAdding = true;
		$user = array();
	} 
	$saveChanges = extractStringWithKeyFromArray("saveChanges", $_REQUEST);
	$name = extractStringWithKeyFromArray("name", $_REQUEST);
	$newpassword = extractStringWithKeyFromArray("newpassword", $_REQUEST);
	$firstName = extractStringWithKeyFromArray("firstName", $_REQUEST);
	$surname = extractStringWithKeyFromArray("surname", $_REQUEST);
	$email = extractStringWithKeyFromArray("email", $_REQUEST);
	if ($saveChanges) {
		$db->executeQuery("SELECT * FROM user WHERE username='".$name."'");
		if($db->numRows() > 0 && $isAdding) {
			$wname = "Username already exists!";
			$saveChanges = false;
		} elseif (!$name) {
			$wname = "Please enter a name!";
			$saveChanges = false;
		} elseif ((!$newpassword) && ($isAdding)) {
			$wpassword = "Please enter a password!";
			$saveChanges = false;
		} elseif (!$firstName) {
			$wfirstName = "Please enter a first name";
			$saveChanges = false;
		} elseif (!$surname) {
			$wsurname = "Please enter a surname";
			$saveChanges = false;			
		} elseif (!$email || !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email)) {
			$wemail = "Please enter a valid email";
			$saveChanges = false;			
		}
	}
?>
<script language="javascript" type="text/javascript">

function addGroup()
{
	var selected = document.userForm.group.selectedIndex;
	var toAddText = document.userForm.group[selected].text;
	var toAddValue = document.userForm.group.value;
	var newOpt = new Option(toAddText, toAddValue);
	var lengthList = document.userForm.userGroup.length;
	document.userForm.userGroup[lengthList] = newOpt;
	document.userForm.group.remove(selected);

}

function removeGroup() {
	var selected = document.userForm.userGroup.selectedIndex;
	var toAddText = document.userForm.userGroup[selected].text;
	var toAddValue = document.userForm.userGroup.value;
	var newOpt = new Option(toAddText, toAddValue);
	var lengthList = document.userForm.group.length;
	document.userForm.group[lengthList] = newOpt;
	document.userForm.userGroup.remove(selected);
}

function removeNA() {	
	if (document.userForm) {
		if (document.userForm.userGroup[0].text == "N/A") {
			document.userForm.userGroup.remove(0);
			//var blah = document.userForm.userGroup[0].text;
			//alert(blah);
		}
	}
}

function formSubmit() {	
	if (document.forms['userForm'].name.value == "") {
		alert("Please enter a name!");
		document.forms['userForm'].name.select();
<?	
	if($isAdding) {
?>
	} else if (document.forms['userForm'].newpassword.value == "") {
		alert("Please enter a password!");
		document.forms['userForm'].newpassword.select();
<?
	}
?>	
	}
	else {
		var listLength = document.userForm.userGroup.length;
		var groupArray = "";
		for (i=0; i < listLength; i++) {
			if (groupArray == "") {
				groupArray = groupArray + document.userForm.userGroup[i].value;
			}
			else {
				groupArray = groupArray + "," + document.userForm.userGroup[i].value;
			}
		}
		document.userForm.uGroups.value = groupArray;
		document.userForm.submit();
	}
}
</script>
	


<div class="cms_browse_heading">
	<div class="cms_browse_heading_label">
		<h1>Add User</h1>
	</div>
	<div class="cms_browse_addrecord"></div>
</div>
<div id="cms_browse_topdivider" class="cms_browse_divider"></div>
<div id="cms_masteredit">
	<table width="100%" border="0" cellpadding="0" cellspacing="0" class="cms_browsetext">
  		<tr>
  			<td>
        <?
	if (!$error && !$saveChanges) {  
?> 		  
		  <form action="/cms/html/index.php?fileNo=9" method="post" enctype="multipart/form-data" name="userForm" id="userForm">
            <table width="100%" border="0" cellspacing="0" cellpadding="0" class="cms_browsetext">
              
              <tr>
                <td class="body2-7">User Type:</td>
                <td class="body2-1" colspan="2">
<?php
	$userTable = new CmsTableWriter("usertype", $db);
	$userTable->resetIterator();
	echo "<select name=\"userType\" >";
	while ($row = $userTable->nextItem()) {
		if(($row->usertype) >= ($authInfo->usertype)) {
			$selected = "";			
			if ( $row->usertype == 1) $selected = 'selected="yes"';
			echo "<option $selected value=\"".$row->usertype."\">".$row->description."</option>";
		}
	}
	echo "</select>";
?>
<script>
<?php
if (isset($uid) && is_numeric($uid)) {
	echo "var ut = ".$user->usertype.";";
}
else {
	echo "var ut = '';";
}
?>
    for (i=0; i < document.forms['userForm'].elements['userType'].options.length; i++){
            if(document.forms['userForm'].elements['userType'].options[i].value==ut){
                    document.forms['userForm'].elements['userType'].selectedIndex=i;
            }
    }
   
</script>

                </td>
              </tr>
              <tr>
                <td colspan=3><img src="/cms/images/spacer.gif" width="450" height="5"></td>
              </tr>
              <tr>
                <td width="20%" class="body2-7">UserName:</td>
                <td class="body2-1" colspan="2">
		  <?
			if (isset($wname)) {
				echo "<font color='red'>".$wname."</font><br>";
			}
		  ?>
		<input name="name" type="text" value="<?= $user->username ?>" />
		</td>
              </tr>
              <tr>
                <td colspan=3><img src="/cms/images/spacer.gif" width="450" height="5"></td>
              </tr>
              <tr>
                <td width="20%" class="body2-7">Password:</td>
                <td class="body2-1" colspan="2">
		  <?
		  	if (isset($wpassword)) {
		  		echo "<font color='red'>".$wpassword."</font><br>";
		  	}
		  ?>
		  <input type="password" name="newpassword" value="" />
		</td>
              </tr>
              <tr>
                <td colspan=3><img src="/cms/images/spacer.gif" width="450" height="5"></td>
              </tr>
              <tr>
                <td width="20%" class="body2-7">First Name:</td>
                <td class="body2-1" colspan="2"><?
			if (isset($wfirstName)) {
				echo "<font color='red'>".$wfirstName."</font><br>";
			}
		  ?><input type="text" name="firstName" value="<?=$user->firstname?>" /></td>
              </tr>
              <tr>
                <td colspan=3><img src="/cms/images/spacer.gif" width="450" height="5"></td>
              </tr>
              <tr>
                <td width="20%" class="body2-7">Surname:</td>
                <td class="body2-1" colspan="2"><?
			if (isset($wsurame)) {
				echo "<font color='red'>".$wsurname."</font><br>";
			}
		  ?><input type="text" name="surname" value="<?=$user->lastname?>" /></td>
              </tr>
              <tr>
                <td colspan=3><img src="/cms/images/spacer.gif" width="450" height="5"></td>
              </tr>
              <tr>
                <td width="20%" class="body2-7">Email:</td>
                <td class="body2-1" colspan="2"><?
			if (isset($wemail)) {
				echo "<font color='red'>".$wemail."</font><br>";
			}
		  ?><input type="text" name="email" value="<?=$user->email?>" /></td>
              </tr>
              <tr>
                <td colspan=3><img src="/cms/images/spacer.gif" width="450" height="5"></td>
              </tr>
              <tr>
                <td class="body2-7">Group:</td>
                <td class="body2-1" colspan="2"><table cellspacing=0 cellpadding=0>
                    <tr>
                      <td rowspan="2">
<?php
	optionList(array("name"=>"group", "size"=>"5"),false,null,0,1,"SELECT gid, groupname FROM grouplist g",$db);
?>
                      </td>
                      <td>
					  &nbsp;&nbsp;<img src="/cms/images/include.gif" onClick="javascript:addGroup();">&nbsp;&nbsp;
		      </td>
                      <td rowspan="2">
<?php				  
	optionList(array("name"=>"userGroup", "size"=>"5", "multiple"=>"multiple"),false,null,0,1,"SELECT grouplist.gid, grouplist.groupname FROM grouplist, usergroup WHERE grouplist.gid=usergroup.gid AND usergroup.uid=".$uid,$db);
?>
<script>
        for (i=0; i < document.forms['userForm'].elements['userGroup'].options.length; i++){
			for (j=0; j < document.forms['userForm'].elements['group'].options.length; j++){
				var userGroup = document.forms['userForm'].elements['userGroup'];
				var group = document.forms['userForm'].elements['group'];
				if (userGroup.options[i].value == group.options[j].value){
					group.remove(j);
				}
			}
        }
</script>
		      </td>
                    </tr>
                    <tr>
                      <td valign="top">
					  &nbsp;&nbsp;<img src="/cms/images/remove.gif" onClick="javascript:removeGroup();">&nbsp;&nbsp;
		      </td>
                    </tr>
                </table></td>
              </tr>
              <tr>
                <td colspan="3">&nbsp;</td>
              </tr>
              <tr>
                <td width="20%">&nbsp;</td>
                <td width="48%" valign="middle">
                    <a href="javascript:formSubmit();" class="body2-2">Update/Add Now</a></td>
		    <input type="hidden" name="uGroups" value="none" />
                <td width="32%" valign="middle"></td>
              </tr>
            </table>
            <br>
            <br>
	    <input type="hidden" name="saveChanges" value="saveChanges" />
	    <input type="hidden" name="uid" value="<?= $uid ?>" />	    
          </form>
<?
	// if we are adding do this block
	//} else if () {
		
	//if we are editing do this block
	//} else if () {
	
//edit
	} else if (!$error && $saveChanges && !$uid) {
		//echo "add";
			
			/* no primary key here.. as the user table is an auto increment table */
			
			$tableWriter2->begin();
			$tableWriter2->addField("username",$name);
			$tableWriter2->addField("password",md5($newpassword));
			$tableWriter2->addField("usertype",$userType);
			$tableWriter2->addField("firstname", $firstName);
			$tableWriter2->addField("lastname", $surname);
			$tableWriter2->addField("email", $email);
			$tableWriter2->newItem();
			
			if (isset($uGroups) && $uGroups != '') {
				$uGroupsArray = explode(",",$uGroups);
				//find out the uid to send to editUser
				$db->executeQuery("SELECT * FROM user WHERE username='".$name."'");
				$row = $db->nextObject();
				$uid = $row->uid;
				editUser($uGroupsArray,$uid,$db);
			}
			else {
				echo "<br><br>The user has been added.<br>Without any groups.<br><br>";
			}			
		
	} else if (!$error && $saveChanges && $uid) {
		//echo "edit";	
		/*update the user details if necessary.
		call the edit function to update the groups.*/
		$query = "Update user Set usertype='".$userType."', username='".$name."', firstname='".$firstName."', lastname='".$surname."', email='".$email."' ";
		if($newpassword) {
			$query .=", password=md5('".$newpassword."') ";
		}
		$query .= " Where uid='".$uid."' ";
		//echo "Query = $query <br>";
		$db->executeQuery($query);
		
		//have to delete the groups the user belongs to even if uGroups is empty
		// ( to get rid of the last group )
		$query = "DELETE FROM usergroup WHERE uid=".$uid;
		$db->executeQuery($query);
		
		if (isset($uGroups) && $uGroups != '') {
			$uGroupsArray = explode(",",$uGroups);
			editUser($uGroupsArray,$uid,$db);
		} else {
			echo "<br><br>The user has been updated without any groups.<br><br>";
		}
	} else if ($error) {
	dialoguePage(array(	DLG_MESSAGE=> 	$error,
		DLG_LEFT_TEXT=>	DLG_EMPTY,
		DLG_LEFT_LINK=>	CMS_HOME,
		DLG_RIGHT_TEXT=>	DLG_OK,
		DLG_RIGHT_LINK=>	CMS_HOME ));
	}	
?>
		</td>
	</tr>
</table>
</div>